// @Author EthanScriptOn
// @Desc
package extend_param_builder

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_param_collector"
	"net/http"
)

type HttpParamsBuilder struct {
}

func (h *HttpParamsBuilder) Build(params interface{}) (interface{}, error) {
	httpParams, ok := params.(*extend_param_collector.HttpParams)
	if !ok {
		return nil, fmt.Errorf("params is not HttpParams")
	}
	if !httpParams.IsValid() {
		return nil, fmt.Errorf("params is not valid")
	}
	marshalBytes, err := json.Marshal(httpParams.Args)
	req, err := http.NewRequest(httpParams.RequestType, httpParams.Url, bytes.NewBuffer(marshalBytes))
	if err != nil {
		return nil, fmt.Errorf("error creating request: %v", err)
	}
	for headerKey, headerVal := range httpParams.Headers {
		if headerKey == "" {
			continue
		}
		req.Header.Set(headerKey, headerVal)
	}
	return req, nil
}
